package com.cyy.demo.scheduler;

import com.cyy.demo.bussiness.RedisService;
import com.cyy.demo.common.KafkaProducer;
import com.cyy.demo.entity.User;
import com.cyy.demo.utils.BasicRedisPubSub;
import com.cyy.demo.utils.Object2ArrayUtil;
import com.cyy.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import redis.clients.jedis.Jedis;

import java.util.Date;

@Configuration
public class MyTask {

    private int count =0;

    @Autowired
    private RedisService redisService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private KafkaProducer<byte[]> kafkaProducer;


//    @Scheduled(fixedRate=2000)
    public void send(){
        redisService.publish("mytopic","jack"+count);
        System.out.println("定时任务发送消息到reidis成功，第"+count++ +"条");
    }

//    @Scheduled(fixedRate=2000)
    public void send2(){
        Jedis jedis = RedisUtil.getJedis("127.0.0.1", 6379, "admin");
        try {
            for (int i = 0; i < 100; i++) {
                RedisUtil.sendMesage(jedis,"test",i+"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @PostConstruct
    public void receive(){
       new Thread(new Runnable() {
           @Override
           public void run() {
               Jedis jedis = RedisUtil.getJedis("127.0.0.1", 6379, "admin");;
               while (true){
                   try {
                       RedisUtil.receiveMessage(jedis,new BasicRedisPubSub(){
                           @Override
                           public void onMessage(String channel, String message) {
                               System.out.println("接收消息为:"+message);
                           }
                       },"test");
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           }
       }).start();
    }

//    @Scheduled(fixedRate=2000)
    public void addList() {
        stringRedisTemplate.opsForList().rightPush("list", String.valueOf(count++));

    }

//    @Scheduled(fixedRate=2000)
    public void getList() {
//        stringRedisTemplate.opsForList().leftPop("list", 1, TimeUnit.SECONDS);

    }

//    @Scheduled(fixedRate=1000)
    public void sendToKafka() {
        User user = User.builder().id(count++)
                .registerDate(new Date())
                .username("test")
                .password("test")
                .build();
        kafkaProducer.send(Object2ArrayUtil.objectToByteArray(user));
    }
}
